package com.example.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.server.exception.YebException;
import com.example.server.mapper.RoleMapper;
import com.example.server.pojo.Admin;
import com.example.server.mapper.AdminMapper;
import com.example.server.pojo.Role;
import com.example.server.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.server.vo.RespBean;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author CuiQingFeng
 * @since 2022-09-01
 */
@Service
@Transactional
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public RespBean login(Admin admin, HttpSession session) {

        Admin adminFromDb = adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", admin.getUsername()));

        if (adminFromDb != null) {
            if (BCrypt.checkpw(admin.getPassword(), adminFromDb.getPassword())) {

                // 同步该用户对应的所有角色
                List<Role> roles = roleMapper.findAllByAdminId(adminFromDb.getId());
                adminFromDb.setRoles(roles);

                session.setAttribute("auth", adminFromDb);
                // 认证成功的情况
                return RespBean.success(200, "登录成功！");
            }
        }

        throw new YebException(402, "用户名或者密码不正确！");
    }
}
